package com.muyan.common.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.muyan.common.constant.Const.UTF_8;

/**
 * 读写文件
 */
public class IOUtil {

    /**
     * 读取字符串，默认都是UTF-8编码
     */
    public static String read(File file, String encode) {
        String res = "";
        try (FileInputStream fs = new FileInputStream(file)) {
            res = read(fs, encode);
        } catch (IOException io) {
            io.printStackTrace();
        }
        return res;
    }

    public static String read(InputStream input, String encode) throws IOException {
        if (StrUtil.isBlank(encode)) encode = UTF_8;
        StringBuilder str = new StringBuilder();
        try (
                InputStreamReader isr = new InputStreamReader(input, encode);
                BufferedReader br = new BufferedReader(isr);
        ) {
            String data;
            while ((data = br.readLine()) != null) {
                str.append(data).append('\n');
            }
            return str.toString();
        }
    }

    /**
     * 按行正向读取文件
     */
    public static List<String> headList(File file, Integer lines, String encode) throws Exception {
        encode = StrUtil.isBlank(encode) ? UTF_8 : encode;
        return headList(new FileInputStream(file), lines, encode);
    }

    /**
     * 按行正向读取文件
     */
    public static List<String> headList(InputStream is, Integer lines, String encode) throws Exception {
        encode = StrUtil.isBlank(encode) ? UTF_8 : encode;
        List<String> r = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, encode))) {
            String line;
            int ed = 0;
            while (null != (line = reader.readLine())) {
                if (lines != null && lines < (++ed)) break;
                r.add(line);
            }
            return r;
        }
    }

    /**
     * 逆向读取文件末尾行
     */
    public static List<String> tailList(File file, int lines, String encode) {
        if (StrUtil.isBlank(encode)) encode = UTF_8;
        List<String> result = new ArrayList<>();
        if (!file.exists() || file.isDirectory() || !file.canRead()) return result;
        int count = 0;
        try (RandomAccessFile rf = new RandomAccessFile(file, "r")) {
            long length = rf.length();// 读取文件长度
            if (length == 0L) {// 如果是0，代表是空文件，直接返回空结果
                return result;
            } else {
                long pos = length - 1;// 初始化游标
                while (pos > 0) {
                    pos--;
                    rf.seek(pos);// 开始读取
                    if (rf.readByte() == '\n') {// 如果读取到\n代表是读取到一行
                        result.add(new String(rf.readLine().getBytes(StandardCharsets.ISO_8859_1), encode));// 保存结果
                        count++;
                        if (count == lines) {// 行数统计，如果到达了指定的行数，就跳出循环
                            break;
                        }
                    }
                }
                if (pos == 0) {//逆序，第一行
                    rf.seek(0);
                    result.add(new String(rf.readLine().getBytes(StandardCharsets.ISO_8859_1), encode));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 覆盖写文件
     */
    public static void write(File file, String content) throws IOException {
        if (file == null) return;
        content = content == null ? "" : content;
        write(file, content, false, UTF_8);
    }

    /**
     * 写文件
     */
    public static void write(File file, String content, boolean append, String encode) throws IOException {
        try (
                FileOutputStream out = new FileOutputStream(file, append);
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encode == null ? UTF_8 : encode));
        ) {
            writer.write(content);
        }
    }

}
